package com.icesoft.core.common.helper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.HashSet;
import java.util.Set;

public abstract class ObjectUtil {

    /**
     * 获取为空的属性名
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 常用方法，把source中不为空的，并且target中存在的，并且相同类型的属性复制到target中
     */
    public static void copyPropertiesIgnoreSourceNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

    /**
     * 把target中不为空的，并且source中存在的，并且相同类型的属性复制到target中
     */
    public static void copyPropertiesIgnoreTargetNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(target));
    }

    public static void copyPropertiesOnlyTargetNull(Object source, Object target) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        final BeanWrapper tag = new BeanWrapperImpl(target);
        java.beans.PropertyDescriptor[] pds = tag.getPropertyDescriptors();
        for (java.beans.PropertyDescriptor pd : pds) {
            if (tag.getPropertyValue(pd.getName()) != null) {
                continue;
            }
            if (src.isReadableProperty(pd.getName())) {
                Object srcValue = src.getPropertyValue(pd.getName());
                tag.setPropertyValue(pd.getName(), srcValue);
            }
        }
    }

}
